<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head th:replace="common/fragment::top">

</head>

<body>
<div class="lyear-layout-web">
    <div class="lyear-layout-container">
        <!--左侧导航-->
        <div th:replace="common/fragment::leftmenu"></div>
        <!--End 左侧导航-->

        <!--头部信息-->
        <div th:replace="common/fragment::header"></div>
        <!--End 头部信息-->

        <!--页面主要内容-->
        <main class="lyear-layout-content">

            <div class="container-fluid">
                <div>
                    <!--订单-->
                    <form action="#!" class="horizontal " id="add-user-form" method="post">
                        <div class="form-group col-md-10 ">
                            <!--订单号-->
                            <label class="col-md-2 control-label" for="sellno"
                                   style="text-align: center;line-height: 36px">订单号</label>
                            <div class="col-md-3">
                                <input class="form-control" id="sellno" name="sellno"
                                       placeholder="订单号" readonly th:value="${sellno}"
                                       type="text">
                            </div>
                            <!--END订单号-->
                            <!--生成日期-->
                            <label class="col-md-2 control-label" for="ctime"
                                   style="text-align: center;line-height: 36px">生成日期</label>
                            <div class="col-md-3">
                                <input class="form-control" id="ctime" name="ctime"
                                       placeholder="生成日期" readonly
                                       th:value="${#dates.format(ctime, 'yyyy-MM-dd')}" type="text">

                            </div>
                            <!--END生成日期-->
                        </div>

                        <div class="form-group col-md-10 ">
                            <!--供应商-->
                            <label class="col-md-2 control-label" for="cust"
                                   style="text-align: center;line-height: 36px">顾客</label>
                            <div class="col-md-3">
                                <select class="form-control" id="cust" name="cust" size="1">
                                    <option th:each="cust:${custlist}" th:text="${cust.name}"
                                            th:value="${cust.id}">请选择
                                    </option>
                                </select>
                            </div>
                            <!--END供应商-->
                            <!--要货日期-->
                            <label class="col-md-2 control-label" for="ctime"
                                   style="text-align: center;line-height: 36px">要货日期</label>
                            <div class="col-md-3">
                                <input class="form-control js-datepicker m-b-10" data-date-format="yyyy-mm-dd"
                                       id="need"
                                       name="need" placeholder="请选择日期(yyyy-mm-dd)" type="text"
                                       value=""/>
                            </div>
                            <!--END要货日期-->
                        </div>
                        <!--注释-->
                        <div class="form-group col-md-10 ">
                            <label class="col-md-2 control-label" for="comment"
                                   style="text-align: center;line-height: 36px">备注</label>
                            <div class="col-md-8">
                                <input class="form-control" id="comment" name="comment"
                                       placeholder=".....备注....." type="text">
                            </div>
                        </div>

                    </form>
                    <!--END订单-->
                    <!--添加明细按钮组-->
                    <div class="form-group col-md-10">
                        <button
                                class="btn-xs btn-info ajax-post col-md-2"
                                id="add-sell-detail-btn"
                                type="button">添加明细
                        </button>
                        <label class="col-md-1 control-label"
                               style="text-align: center;line-height: 36px">合计</label>
                        <label class="col-md-2 control-label" id="totalcomsump"
                               style="text-align: center;line-height: 36px;color: darkblue">0.0</label>
                    </div>
                    <!--END添加明细按钮组-->

                    <!--添加明细-->
                    <div hidden="hidden" id="detail-table">
                        <form action="#!" class="horizontal " id="add-detail-form" method="post">
                            <!--商品条目-->
                            <div class="col-md-3 form-group">
                                <select class="form-control" id="goodlist" name="goodlist" size="1">
                                    <!--                  <option th:each="good:${goodlist}" th:text="${good.name}"-->
                                    <!--                          th:value="${good.id}">请选择-->
                                    <!--                  </option>-->
                                </select>
                            </div>
                            <!--END商品条目-->
                            <!--商品数量-->
                            <div class="col-md-3">
                                <input class="form-control" id="itemcount" name="count"
                                       placeholder="数量"
                                       type="number">
                            </div>
                            <!--END商品数量-->
                            <!--商品单价-->
                            <div class="col-md-3">
                                <input class="form-control" id="itemprice" max="any"
                                       min="0" name="price" pattern="[0-9].[0-9][0-9]"
                                       placeholder="商品单价" type="number">
                            </div>
                            <!--END商品单价-->

                            <!--添加明细条目按钮-->
                            <div class="form-group col-md-1">
                                <button
                                        class="btn-xs btn-info ajax-post"
                                        id="add-item-to-detail-btn"
                                        type="button">添加
                                </button>
                            </div>
                            <!--END添加明细条目按钮-->
                        </form>

                        <!--END添加明细条目-->
                        <table class="table table-bordered">
                            <thead hidden="hidden" id="goodheader">
                            <tr>
                                <!--                <th>序号</th>-->
                                <th hidden="hidden">id</th>
                                <th>名称</th>
                                <!--    <th>角色图标</th>-->
                                <th>商品规格</th>
                                <!--                                            <th>包装</th>-->
                                <th>计量单位</th>
                                <th>单价</th>
                                <th>库存</th>
                                <th>数量</th>

                                <th>计价</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody id="selldetail">
                            </tbody>
                        </table>
                    </div>
                    <!--END添加明细-->

                    <!--生成订单按钮组-->
                    <div class="form-group col-md-10">
                        <button
                                class="btn btn-primary ajax-post col-md-2"
                                id="save-sell-btn"
                                target-form="add-form"
                                type="button">生成订单
                        </button>

                        <button
                                class="btn btn-default col-md-2"
                                onclick="history.back(-1);return false;"
                                type="button">返 回
                        </button>
                    </div>
                    <!--END生成订单按钮组-->

                    <table hidden="hidden" id="repoinfogoodcount">
                        <tr th:each="repo:${repolist}">
                            <td class="repogoodid" th:text="${repo.goodPO.id}"></td>
                            <td class="repogoodcount" th:text="${repo.goodcount}"></td>
                        </tr>
                    </table>
                </div>
            </div>
        </main>
        <!--End 页面主要内容-->
    </div>
</div>

<div th:insert="common/fragment::tail-script"></div>
<!--日期选择插件-->
<script th:src="@{/static/admin/js/bootstrap-datepicker/bootstrap-datepicker.min.js}"></script>
<link rel="stylesheet"
      th:src="@{/static/admin/js/bootstrap-datepicker/bootstrap-datepicker3.min.js}">
<link rel="stylesheet" th:href="@{/static/admin/css/style.min.css}">
<style>
    .lessgood {
        color: #ac2925;
        font-weight: bolder;
        text-decoration-line: line-through;
    }
</style>
<script type="text/javascript">
    //商品计量单位
    let UNIT_CASE = []
    UNIT_CASE.push({0:"散装"})
    UNIT_CASE.push({1:"包"})
    UNIT_CASE.push({2:"公斤"})
    UNIT_CASE.push({3:"吨"})
    UNIT_CASE.push({4:"件"})
    UNIT_CASE.push({5:"套"})
    let  repoinfomap = new Map
    $(document).ready(function () {
// 库存信息

        $('#repoinfogoodcount tr').each(function (i,e) {
            let goodid = $(e).children('.repogoodid').text()
            let goodcount = $(e).children('.repogoodcount').text()
            repoinfomap.set(parseInt(goodid),parseInt(goodcount))
        })

// 剩余的明细条目
        let sell = null
// 剩余的明细条目
        let retainary = []

// 商品列表
        let vgoodlist = [] // ajax获取,ajax初始为供应商所支持的所有商品

// 商品列表完整
        let vallgoodlist = [] // ajax获取,ajax初始为供应商所支持的所有商品 -- 保留不动

// 要移除的商品
        let vremovalgood = null

        // 商品下拉菜单数据
        let vgoodmenulist = []

        // 明细数据
        let vdetaillist = []
        let removeid = null

// 合计订单金额
/*        let totalcomsump = 0.0*/
        function showTotal(){
            let total = 0
            for(let i = 0;i<vdetaillist.length;i++){
                total = total + vdetaillist[i].price*vdetaillist[i].count
            }
            total = total.toFixed(2)

            $('#totalcomsump').text(total)
        }

// 允许添加细目
// ajax初始化商品列表 vgoodlist 和 vallgoodlist
        $('#add-sell-detail-btn').click(function () {
            let sellno = $('#sellno').val()
            let ctime = $('#ctime').val()
            let need = $('#need').val()
            let cust = $('#cust').val()
            let comment = $('#comment').val()

            sell = {
                id: '',
                name: sellno,
                createTime: ctime,
                need: need,
                comment: comment,
                custPO: {id: cust}
            }
            console.log(sell)

            // 验证订单条目
            if (sellno === '') {
                confirmMsg('订单好不正确')
                return false;
            }

            if (ctime === '') {
                confirmMsg('建档日期不正确')
                return false;
            }

            if (need === '') {
                confirmMsg('请选择需货日期')
                return false;
            }

            if (cust === '') {
                confirmMsg('请选择顾客')
                return false;
            }

            // 给订单设只读
            $('#sellno').attr('readonly', true)
            $('#ctime').attr('readonly', true)
            $('#need').attr('disabled', 'disabled')
            $('#cust').attr('disabled', 'disabled')
            $('#comment').attr('readonly', true)

            let data = null

            // 通过ajax 生成 商品菜单列表列表
            $.ajax({
                type: "POST",
                contentType: "application/json;charset=utf-8",
                dataType: "json",
                url: "/sell/getGoodlist.ajax",
                async:false,
                data: null,
                success: function (result) {
                    if (result.code === 200) {
                        let temp = result.data.goodlist
                        for(let i=0;i<temp.length;i++){
                            vgoodlist.push(temp[i].goodPO)
                            vallgoodlist.push(temp[i].goodPO)
                        }


                        $('#goodlist').empty()
                        let html = ''
                        for (let i = 0; i < vgoodlist.length; i++) {
                            html += '<option value="' + vgoodlist[i].id + '">' + vgoodlist[i].name + ' | 包装:'
                                + vgoodlist[i].spec + ' | 单位:' + vgoodlist[i].unit + '</option>'

                        }
                        $('#goodlist').append(html)

                    } else {
                        $.confirm({
                            title: '警告',
                            content: result.msg,
                            type: 'orange',
                            typeAnimated: false,
                            buttons: {
                                close: {
                                    text: '关闭',
                                }
                            }
                        });
                    }
                },
                error: function (result) {
                    $.confirm({
                        title: '警告',
                        content: '无法链接服务器啊',
                        type: 'orange',
                        typeAnimated: false,
                        buttons: {
                            close: {
                                text: '关闭',
                            }
                        }
                    });
                }

            });
            // END ajax
            $('#detail-table').attr('hidden', false);
        });
// END允许添加细目

// 添加商品到明细
        $('#add-item-to-detail-btn').click(function () {
            if (vgoodlist == null || vgoodlist.length <= 0) {
                confirmMsg("已添加供应商的全部商品")
                return false;
            }

            let goodid = $('#goodlist').val()
            let itemcount = $('#itemcount').val()
            let itemprice = $('#itemprice').val()
            // 验证
            if (goodid === '') {
                confirmMsg('请选择商品')
                return false;
            }
            if (itemcount === '' || itemcount < 0) {
                confirmMsg('数量不正确')
                return false;
            }
            if (itemprice === '' || itemprice < 0) {
                confirmMsg('价格不正确')
                return false;
            }
            let tmpary = [] // 临时商品列表,减去要添加的商品
            let good = null // 要添加的商品
            // 取 商品值 生成临时数组,在原商品数组的基础上减去提取的数组
            for (let i = 0; i < vgoodlist.length; i++) {

                if (vgoodlist[i].id == goodid) {
                    good = vgoodlist[i]

                } else {
                    tmpary.push(vgoodlist[i])
                }
            }

            // 重置vgoodlist
            vgoodlist = []
            for (let i = 0; i < tmpary.length; i++) {
                vgoodlist.push(tmpary[i])
            }
            // 重置商品列表
            $('#goodlist').empty()
            let html = ''
            for (let i = 0; i < vgoodlist.length; i++) {
                html += '<option value="' + vgoodlist[i].id + '">' + vgoodlist[i].name + ' | 包装:'
                    + vgoodlist[i].spec + ' | 单位:' + UNIT_CASE[vgoodlist[i].unit] + '</option>'

            }
            $('#goodlist').append(html)

            html = ''
            // 打开明细标题
            $('#goodheader').attr('hidden', false)

            let itemgoodid = good['id']
            let itemgoodname = good['name']
            let itemgoodspec = good['spec']
            let itemgoodunit = good['unit']
            let repogoodcount  =repoinfomap.get(itemgoodid);


            // 点击到明细列表
            let detail = {
                id: null,
                good:{
                    id:itemgoodid,
                    name: itemgoodname,
                    spec: itemgoodspec,
                    unit: itemgoodunit
                },
                repogoodcount: repogoodcount,
                price: itemprice,
                count: itemcount
            }
            vdetaillist.push(detail)

            html += '<tr>'
            html += '<td hidden="hidden" class="itemid">' + detail.id + '</td>'
            html += '<td hidden="hidden" class="itemgoodid">' + detail.good.id + '</td>'
            html += '<td class="itemgoodname">' + detail.good.name + '</td>'
            html += '<td class="itemgoodspec">' + detail.good.spec + '</td>'
            html += '<td class="itemgoodunit">' + detail.good.unit + '</td>'
            html += '<td class="itemprice">' + detail.price + '</td>'
            html += '<td class="repogoodcount">' + detail.repogoodcount + '</td>'
            html += '<td class="itemcount">' + detail.count + '</td>'
            html += '<td class="itemsum">' + detail.price * detail.count + '</td>'
            html += ' <td>\n'
                + '                  <div class="btn-group">\n'
                + '                    <a class="btn btn-xs btn-default removegood"\n'
                + '                       data-toggle="tooltip"\n'
                + '\n'
                + '                       href="#" val="' + detail.good.id + '" title="移除">\n'
                + '                      <i class="mdi mdi-alert-outline"></i>\n'
                + '                    </a>\n'
                + '                  </div>\n'
                + '                </td>'
            html += '</tr>'

            $('#selldetail').append(html)
            // 缺货 添加类 lessgood 行显示红色
            $('#selldetail tr').each(function (i,e) {
                let tmprepogoodcount = $(e).children('.repogoodcount').text()
                let tmpitemcount = $(e).children('.itemcount').text()
                if(parseInt(tmprepogoodcount)<parseInt(tmpitemcount)){
                    $(this).addClass('lessgood')
                }else
                {
                    $(this).removeClass('lessgood')
                }

            })
            //END 缺货 添加类 lessgood 行显示红色
            showTotal()
        });
// END添加商品到明细

// 细目中的移除按钮

        $('#selldetail').on('click', '.removegood', function (e) {
            removeid = $(this).attr('val')

            // 重新生成商品下拉列表
            let tmp = null
            for (let i = 0; i < vallgoodlist.length; i++) {
                if (parseInt(vallgoodlist[i].id) === parseInt(removeid)) {
                    vgoodlist.push(vallgoodlist[i])
                    break
                }
            }


            $('#goodlist').empty()
            let html = ''
            for (let i = 0; i < vgoodlist.length; i++) {
                html += '<option value="' + vgoodlist[i].id + '">' + vgoodlist[i].name + ' | 包装:'
                    + vgoodlist[i].spec + ' | 单位:' + vgoodlist[i].unit + '</option>'

            }
            $('#goodlist').append(html)


            // 获取明细条目 不包含要删除的
            retainary = []
            for (let i = 0; i < vdetaillist.length; i++) {

                if (parseInt(vdetaillist[i].good.id) !== parseInt(removeid)) {
                    retainary.push(vdetaillist[i])

                }
            }
            vdetaillist = []
            for (let i = 0; i < retainary.length; i++) {
                vdetaillist.push(retainary[i])
            }


            // 重新生成明细表格
            // 如果是空表
            html = ''
            if (retainary == null || retainary.length <= 0) {
                $('#selldetail').empty()
                $('#goodheader').attr('hidden', true)
                showTotal()
                e.preventDefault()
                return false;
            } else {
                // 非空则重新生成明细表格
                for (let i = 0; i < retainary.length; i++) {
                    let itemid = retainary[i]['id']
                    let itemgoodid = retainary[i].good.id
                    let itemgoodname = retainary[i].good.name
                    let itemgoodspec = retainary[i].good.spec
                    let itemgoodunit = retainary[i].good.unit
                    let itemprice = retainary[i]['price']
                    let repogoodcount = retainary[i]['repogoodcount']
                    let itemcount = retainary[i]['count']

                    html += '<tr>'
                    html += '<td hidden="hidden" class="itemid">' + itemid + '</td>'
                    html += '<td hidden="hidden" class="itemgoodid">' + itemgoodid + '</td>'
                    html += '<td class-"itemgoodname">' + itemgoodname + '</td>'
                    html += '<td class-"itemgoodspec">' + itemgoodspec + '</td>'
                    html += '<td class-"itemgoodunit">' + itemgoodunit + '</td>'
                    html += '<td class-"itemprice">' + itemprice + '</td>'
                    html += '<td class="repogoodcount">' + repogoodcount + '</td>'
                    html += '<td class-"itemcount">' + itemcount + '</td>'
                    html += '<td class-"itemsum">' + itemcount * itemprice + '</td>'
                    html += ' <td>\n'
                        + '                  <div class="btn-group">\n'
                        + '                    <a class="btn btn-xs btn-default removegood"\n'
                        + '                       data-toggle="tooltip"\n'
                        + '\n'
                        + '                       href="#" val="' + itemgoodid + '" title="移除">\n'
                        + '                      <i class="mdi mdi-alert-outline"></i>\n'
                        + '                    </a>\n'
                        + '                  </div>\n'
                        + '                </td>'
                    html += '</tr>'
                }
                $('#selldetail').empty()
                $('#selldetail').append(html)
                showTotal()
                e.preventDefault()
                return false;
            }


            e.preventDefault()
        })


// END细目中的移除按钮

// 货币保留2位,不小于0
        $('#itemprice').blur(function () {
            let val = parseFloat($('#itemprice').val())
            if (val == null || val == 'NaN') {
                $(this).val(0)
                return
            }

            val = val.toFixed(2)

            if (val < 0) {
                confirmMsg("输入单价有误")
            }
            $(this).val(val)

            //set the numeric value to a number input
            // $(this).value = this.value.replace(/,/g, "")
        });
//END货币保留2位

// 数量为整数,不小于0
        $('#itemcount').blur(function () {
            let val = parseInt($('#itemcount').val())

            if (val == null || val == 'NaN') {
                $(this).val(0)
                return
            }

            if (val < 0) {
                confirmMsg("输入单价有误")
            }
            $(this).val(val)

        });
//END数量为整数,不小于0

// 保存订单
        $('#save-sell-btn').click(function () {
            let selldetaillist = []
            for (let i = 0; i < vdetaillist.length; i++) {
                let price = vdetaillist[i].price
                let count = vdetaillist[i].count
                let good = {id: vdetaillist[i].good.id}
                let tmp = {
                    price: price,
                    goodcount: count,
                    goodPO: good
                }
                selldetaillist.push(tmp);
            }
            let data = {
                id: null,
                name: sell.name,
                createTime: sell.createTime,
                need: sell.need,
                comment: sell.comment,
                custPO: sell.custPO,
                sellDetailPOList: selldetaillist
            }

            post_ajax("/sell/savesellPO.ajax", data, "/sell/selllist.do")
        });
// END保存订单
    });

</script>
</body>
</html>